package org.yunai.swjg.server.module.user.operation;

import org.yunai.swjg.server.core.session.GameSession;
import org.yunai.swjg.server.entity.User;
import org.yunai.swjg.server.module.idSequence.IdSequenceHolder;
import org.yunai.swjg.server.module.user.UserMapper;
import org.yunai.swjg.server.rpc.message.S_C.S_C_RegisterResp;
import org.yunai.yfserver.async.IIoOperation;
import org.yunai.yfserver.spring.BeanManager;

/**
 * 用户帐号注册查询Io操作
 * User: yunai
 * Date: 13-3-30
 * Time: 下午3:20
 */
public class UserRegisterIoOperation implements IIoOperation {

    private static UserMapper userMapper;

    static {
        UserRegisterIoOperation.userMapper = BeanManager.getBean(UserMapper.class);
    }

    private volatile GameSession session;

    private final String userName;
    private final String password;

    private volatile User user;
    /**
     * 注册结果<br />
     * 0 - 注册成功
     * 1 - 注册失败，用户已经存在
     */
    private volatile Byte result;

    public UserRegisterIoOperation(GameSession session, String userName, String password) {
        this.session = session;
        this.userName = userName;
        this.password = password;
    }

    @Override
    public State doStart() {
        return State.STARTED;
    }

    @Override
    public State doIo() {
        user = userMapper.selectUserByUserName(userName);
        if (user == null) {
            user = new User();
            user.setId(IdSequenceHolder.COMMON_USER_ID.getAndIncrement());
            user.setUserName(userName);
            user.setPassword(password);
            userMapper.insertUser(user);

            result = 0;
        } else {
            result = 1;
        }
        return State.IO_DONE;
    }

    @Override
    public State doFinish() {
        if (result != null) {
            session.write(new S_C_RegisterResp(result));
        }
        return State.FINISHED;
    }
}
